package com.xyz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xyz.entity.mapper.RepairWorkOrderMapper;
import com.xyz.entity.mapper.SystemEmployeeMapper;
import com.xyz.entity.mapper.SystemRoleMapper;
import com.xyz.entity.mapper.SystemUserMapper;
import com.xyz.entity.pojo.*;
import com.xyz.service.CommonService;
import com.xyz.service.EmployeeService;
import com.xyz.util.dto.DataResult;
import com.xyz.util.dto.GridData;
import com.xyz.util.dto.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private SystemEmployeeMapper systemEmployeeMapper;

    @Autowired
    private SystemRoleMapper systemRoleMapper;

    @Autowired
    private RepairWorkOrderMapper repairWorkOrderMapper;

    @Override
    public DataResult selectEmployee(LoginInfo li, int pageNum, int pageSize, String employeeName, String roleId) throws Exception {
        SystemRoleExample srExample = new SystemRoleExample();
        srExample.createCriteria().andIsDeleteEqualTo(0);
        List<SystemRole> srList = systemRoleMapper.selectByExample(srExample);
        Map<Long, String> srMap = new HashMap<>();
        for (SystemRole sr : srList) {
            srMap.put(sr.getId(), sr.getRoleName());
        }

        SystemUserExample suExample = new SystemUserExample();
        suExample.createCriteria().andIsDeleteEqualTo(0);
        List<SystemUser> suList = systemUserMapper.selectByExample(suExample);
        Map<Long, SystemUser> suMap = new HashMap<>();
        for (SystemUser su : suList) {
            suMap.put(su.getEmployeeId(), su);
        }

        SystemEmployeeExample seExample = new SystemEmployeeExample();
        SystemEmployeeExample.Criteria seCriteria = seExample.createCriteria();
        if (StrUtil.isNotBlank(employeeName)) {
            seCriteria.andEmployeeNameLike("%" + employeeName + "%");
        }
        if (StrUtil.isNotBlank(roleId)) {
            suExample.clear();
            suExample.createCriteria().andRoleIdEqualTo(Long.parseLong(roleId));
            List<SystemUser> suList2 = systemUserMapper.selectByExample(suExample);
            List<Long> idList = new ArrayList<>();
            idList.add(0L);
            for (SystemUser su : suList2) {
                idList.add(su.getEmployeeId());
            }
            seCriteria.andIdIn(idList);
        }
        seCriteria.andIsDeleteEqualTo(0);
        suExample.setOrderByClause("create_time");
        Page<SystemUser> page = PageHelper.startPage(pageNum, pageSize);
        List<SystemEmployee> seList = systemEmployeeMapper.selectByExample(seExample);
        List<Map<String, Object>> list = new ArrayList<>();
        for (SystemEmployee se : seList) {
            SystemUser su = suMap.get(se.getId());
            Map<String, Object> map = new HashMap<>();
            map.put("id", se.getId());
            map.put("phoneNumber", se.getPhoneNumber());
            map.put("position", se.getPosition());
            map.put("employeeName", se.getEmployeeName());
            map.put("headFileCode", se.getHeadFileCode());
            map.put("isMessage", se.getIsMessage());
            map.put("username", su == null ? "" : su.getUsername());
            map.put("roleName", su == null ? "" : srMap.getOrDefault(su.getRoleId(), ""));
            map.put("createTime", DateUtil.formatDateTime(se.getCreateTime()));
            map.put("teamGroup", se.getTeamGroup() == null ? null:Integer.parseInt(se.getTeamGroup()));
            list.add(map);
        }
        return DataResult.build9100(new GridData(page.getTotal(), list));
    }

    @Override
    public DataResult ruleFreeTimeList(LoginInfo li, int pageNum, int pageSize, String employeeTime) throws Exception {
        //根据时间查询出工单在工状态的员工id
        List<Long> idList = repairWorkOrderMapper.ruleFreeTimeWorkList(employeeTime);
        //查询员工表所有员工
        PageHelper.startPage(pageNum, pageSize);
        List<SystemEmployee> employeeList = systemEmployeeMapper.roleList();
        //过滤掉employeeList里id等于idList的数据
        List<SystemEmployee> employees = employeeList.stream()
                .filter(employee -> !idList.contains(employee.getId()))
                .collect(Collectors.toList());
        PageInfo<SystemEmployee> page = new PageInfo<>(employeeList);
        return DataResult.build9100(new GridData(page.getTotal(), employees));
    }

    @Override
    public DataResult insertEmployee(LoginInfo li, String employeeName, String phoneNumber,
                                     int position, String headFileCode, int isMessage,String teamGroup) throws Exception {
        SystemEmployeeExample seExample = new SystemEmployeeExample();
        SystemEmployeeExample.Criteria seCriteria = seExample.createCriteria();
        seCriteria.andPhoneNumberEqualTo(phoneNumber);
        seCriteria.andIsDeleteEqualTo(0);
        int count = (int) systemEmployeeMapper.countByExample(seExample);
        if (count > 0) {
            return DataResult.build9250("新增失败，手机号重复");
        }

        Date date = new Date();
        SystemEmployee newSe = new SystemEmployee();
        newSe.setEmployeeName(employeeName);
        newSe.setPhoneNumber(phoneNumber);
        newSe.setPosition(position);
        newSe.setHeadFileCode(StrUtil.isBlank(headFileCode) ? "" : headFileCode);
        newSe.setIsMessage(isMessage);
        newSe.setIsDelete(0);
        newSe.setCreateTime(date);
        newSe.setTeamGroup(teamGroup);
        systemEmployeeMapper.insert(newSe);
        // 加载员工数据
        commonService.updateEmployeeMap();
        return DataResult.build9100();
    }

    @Override
    public DataResult updateEmployee(LoginInfo li, long employeeId, String employeeName,
                                     String phoneNumber, int position, String headFileCode, int isMessage,String teamGroup) throws Exception {
        if (employeeId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }

        SystemEmployeeExample seExample = new SystemEmployeeExample();
        SystemEmployeeExample.Criteria seCriteria = seExample.createCriteria();
        seCriteria.andIdNotEqualTo(employeeId);
        seCriteria.andPhoneNumberEqualTo(phoneNumber);
        seCriteria.andIsDeleteEqualTo(0);
        int count = (int) systemEmployeeMapper.countByExample(seExample);
        if (count > 0) {
            return DataResult.build9250("修改失败，手机号重复");
        }

        SystemEmployee newSe = new SystemEmployee();
        newSe.setId(employeeId);
        newSe.setEmployeeName(employeeName);
        newSe.setPhoneNumber(phoneNumber);
        newSe.setPosition(position);
        newSe.setHeadFileCode(StrUtil.isBlank(headFileCode) ? "" : headFileCode);
        newSe.setIsMessage(isMessage);
        newSe.setTeamGroup(teamGroup);
        systemEmployeeMapper.updateByPrimaryKeySelective(newSe);
        // 加载员工数据
        commonService.updateEmployeeMap();
        return DataResult.build9100();
    }

    @Override
    public DataResult deleteEmployee(LoginInfo li, long employeeId) throws Exception {
        if (employeeId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }

        SystemUser newSu = new SystemUser();
        newSu.setEmployeeId(0L);
        SystemUserExample suExample = new SystemUserExample();
        suExample.createCriteria().andEmployeeIdEqualTo(employeeId);
        systemUserMapper.updateByExampleSelective(newSu, suExample);

        SystemEmployee newSe = new SystemEmployee();
        newSe.setId(employeeId);
        newSe.setIsDelete(1);
        systemEmployeeMapper.updateByPrimaryKeySelective(newSe);
        // 加载员工数据
        commonService.updateEmployeeMap();
        return DataResult.build9100();
    }

    @Override
    public DataResult updateEmployeeUser(LoginInfo li, long employeeId, long userId) throws Exception {
        if (employeeId == 1L || userId == 1L) {
            return DataResult.build9250("超级管理员无法修改或删除");
        }
        SystemUser newSu1 = new SystemUser();
        newSu1.setEmployeeId(0L);
        SystemUserExample suExample = new SystemUserExample();
        suExample.createCriteria().andEmployeeIdEqualTo(employeeId);
        systemUserMapper.updateByExampleSelective(newSu1, suExample);
        if (userId != 0L) {
            SystemUser newSu2 = new SystemUser();
            newSu2.setId(userId);
            newSu2.setEmployeeId(employeeId);
            systemUserMapper.updateByPrimaryKeySelective(newSu2);
        }
        return DataResult.build9100();
    }

}
